package com.bxj.wxtt.scheduler;

import com.bxj.wxtt.api.domain.Task;
import com.bxj.wxtt.api.service.ITaskDubboService;
import com.bxj.wxtt.spider.ChannelPageProcessor;
import com.bxj.wxtt.spider.DataBasePipeline;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.pipeline.ConsolePipeline;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by baixiujiang on 18/7/17.
 */
@Component
public class SpiderSheduler {

    @Resource
    ApplicationContext applicationContext;

    @Resource
    DataBasePipeline dataBasePipeline;

    @Resource
    ITaskDubboService taskDubboService;

    Logger logger = LoggerFactory.getLogger(this.getClass());
    //每5分钟启动
//    @Scheduled(fixedRate = 5 * 60 * 1000)
    @Scheduled(initialDelay = 1 * 1000, fixedRate = 600 * 1000)
    public void spiderRun() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        logger.info("spiderRun start ...");
        System.out.println("now time:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        Task queryTask = new Task();
        queryTask.setEnable(1);
        queryTask.setOrderByClause("status desc");
        List<Task> list = taskDubboService.getTaskList(queryTask);
        for (Task task : list) {
            task.setStatus(2);
            task.setUpdateTime(new Date());
            taskDubboService.updateTaskById(task);

            try {
                ChannelPageProcessor processor = (ChannelPageProcessor) Class.forName(task.getClassName()).newInstance();
                processor.setChannelId(task.getChannelId());
                processor.setSiteName(task.getName());
                processor.setContext(applicationContext);
                Spider.create(processor).addUrl(task.getUrl()).addPipeline(new ConsolePipeline())
                        .addPipeline(dataBasePipeline).thread(task.getThread()).run();
            } catch (Exception e) {
                e.printStackTrace();
            }
            task.setStatus(1);
            task.setUpdateTime(new Date());
            taskDubboService.updateTaskById(task);
        }


    }
}
